package com.bdqn.oa.dao.impl;

import com.bdqn.oa.dao.DepartmentDao;
import com.bdqn.oa.entity.Department;
import com.bdqn.oa.utils.DruidUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import java.sql.SQLException;
import java.util.List;

public class DepartmentDaoImpl implements DepartmentDao {
    QueryRunner queryRunner = new QueryRunner();
    /**
     * 返回部门信息集合
     *
     * @return
     */
    @Override
    public List<Department> listgetAllDepartmentInfo() throws SQLException {
        String sql = "select id,name,employee_id as employee_id from department;";
        return queryRunner.query(DruidUtils.getConnection(),sql,new BeanListHandler<Department>(Department.class));
    }

    /**
     * 修改部门名字（Department里传 id, name）
     *
     * @param department
     * @return
     */
    @Override
    public int updateDepartmentName(Department department) throws SQLException {
        String sql = "update department set name = ? where id = ?;";
        return queryRunner.update(DruidUtils.getConnection(),sql,department.getName(),department.getId());
    }

    /**
     * 修改部门领导的id（Department里传 id,Employeeid）
     *
     * @param department
     * @return
     */
    @Override
    public int updateDepartmentEmployeeid(Department department) throws SQLException {
        String sql = "update department set employee_id = ? where id = ?;";
        return queryRunner.update(DruidUtils.getConnection(),sql,department.getEmployeeId(),department.getId());
    }

    /**
     * 增加部门(可以同时定下领导ID)（Department里传 name,employid可以传可以不传）
     *
     * @param department
     * @return
     */
    @Override
    public int insertDepartment(Department department) throws SQLException {
        if (department.getName() != null && department.getEmployeeId() != null){
            String sql = "insert into department (`name`,`employee_id`) VALUE(?,?);";
            return queryRunner.update(DruidUtils.getConnection(),sql,department.getName(),department.getEmployeeId());
        }
        String sql = "insert into department (`name`) VALUE(?);";
        return queryRunner.update(DruidUtils.getConnection(),sql,department.getName());
    }



    /**
     * 通过部门id删除部门
     *
     * @param id
     * @return
     */
    @Override
    public int deleteDepartment(Integer id) throws SQLException {
        String sql = "delete from department where id = ?;";
        return queryRunner.update(DruidUtils.getConnection(),sql,id);
    }
}
